package com.googlecode.imanager.swing.form;

import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.googlecode.imanager.client.bridge.form.IListBox;
import com.googlecode.imanager.client.form.InputList;
import com.googlecode.imanager.client.form.ListBox;
import com.googlecode.imanager.core.base.BridgeApplication;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class SwingListBox<T> extends SwingInputList<T> implements IListBox<T> {

    private JList targetList;
    
    public SwingListBox(BridgeApplication bridge, InputList<T> source) {
        super(bridge, source);
    }

    @Override
    protected void buildImplementation() {
        super.buildImplementation();
        targetList = createTargetList();
        getTarget().setViewportView(targetList);
    }

    @Override
    protected void doAttachEvents() {
        super.doAttachEvents();
        getTargetList().addListSelectionListener(new ListSelectionListener() {    
            @Override
            public void valueChanged(ListSelectionEvent e) {
                synchronized (TREE_LOCK) {
                    if (!isDropped()){
                        startFireUIEvent();
                        try {
                            getSource().setSelectedIndex(getTargetList().getSelectedIndex());
                        } catch (Exception ex) {
                            processException(ex);
                        } finally {
                            endFireUIEvent();
                        }
                    }
                }
            }
        });
    }

    protected JList createTargetList() {
        return new JList(getModel());
    }

    @Override
    protected JScrollPane createTarget() {
        return new JScrollPane();
    }

    @Override
    public JScrollPane getTarget(){
        return (JScrollPane) target;
    }
    
    public javax.swing.JList getTargetList(){
        return (javax.swing.JList) targetList;
    }
    
    @Override
    public JComponent getTargetFocus() {
        return targetList;
    }

    @Override
    public JComponent getTargetKeyEvent() {
        return targetList;
    }

    @Override
    public JComponent getTargetMouseEvent() {
        return targetList;
    }

    @Override
    @SuppressWarnings("unchecked")
    public ListBox<T> getSource() {
        return (ListBox<T>) source;
    }

    @Override
    public void setSelectedIndex(int selectedIndex) {
        if (selectedIndex != getTargetList().getSelectedIndex()){
            if (selectedIndex != -1){
                getTargetList().setSelectedIndex(selectedIndex);
            } else {
                getTargetList().setSelectedIndices(new int[0]);
            }
        }
    }

}
